import useAppStore from '~/stores/app'
import useUserStore from '~/stores/user'
import { popupEnum } from '~/enums/app'
import type { VideoFormData, VideoOptions, VideoConfigs } from '../types/video'
import videoApi from '~/api/apply/video/index'


export const option: Ref<VideoOptions[]> = ref([])               // 视频接口
export const config: Ref<VideoConfigs> = ref({} as VideoConfigs) // 视频配置
export const createLoading: Ref<boolean> = ref(false)            // 生成动画

// 表单数据
export const formData: Ref<VideoFormData> = ref({
    // 视频引擎: [luma, zhipu]
    engine: 'luma',
    // 视频描述
    prompt: '',
    // 视频比例
    scale: '',
    // 参考图片
    image_url: '',
    // 其它参数
    other_params: {}
})

export const queryParams = reactive<{ status: number, engine: string }>({
    engine: formData.value.engine,
    status: -1
})

/**
 * 获取视频记录
 */
export const { pager, queryLists } = usePaging({
    fetchFun: videoApi.record,
    params: queryParams
})

/**
 * 获取视频配置
 */
export const getVideoConfig = async (): Promise<void> => {
    const data: VideoConfigResponse = await videoApi.config(formData.value.engine)
    option.value = data.options
    config.value = data.configs
}

/**
 * 重置视频参数
 *
 * @param {Partial<DrawFormData>} params
 * @author zero
 */
export const resetFormData = async (params?: any): Promise<void> => {
    queryParams.engine = params?.engine || ''
    if (params) {
        formData.value = {
            ...formData.value,
            ...params
        }
    }
}

/**
 * 生成视频任务
 */
export const generate = async (data: any): Promise<void> => {
    const appStore = useAppStore()
    const userStore = useUserStore()
    if (!userStore.isLogin) {
        return appStore.setPopup(popupEnum.LOGIN)
    }

    try {
        end()
        queryParams.engine = data.engine
        createLoading.value = true
        await videoApi.generate(data)
        await queryLists()
        await getVideoConfig()
        await resetFormData({
            prompt: ''
        })
        setTimeout((): void => {
            createLoading.value = false
        }, 2000)
        start()
    } catch {
        createLoading.value = false
    } finally {
        await resetFormData({prompt: ''})
    }
}

/**
 * 心跳检测完成状态
 */
const checkDrawsStatus = async (): Promise<void> => {
    // 获取任务ID
    const taskIds = pager.lists
        .filter((item: any) => {
            return item.status === 1 || item.status === 0
        })
        .map((item: any) => item.code)

    // 结束心跳任务
    if (taskIds.length <= 0) {
        return end()
    }

    // 更新数据信息
    const results: VideoRecordResponse[] = await videoApi.detection(taskIds)
    results.forEach((item: VideoRecordResponse):void => {
        const code: string = item.code
        for (let i = 0; i < pager.lists.length; i++) {
            if (code === pager.lists[i].code &&
                pager.lists[i].status !== item.status
            ) {
                pager.lists[i] = item
                break
            }
        }
    })
}

/**
 * 心跳检测任务结束
 */
const endDrawsCallback = async (): Promise<void> => {
    end()
    const userStore = useUserStore()
    await userStore.getUser()
    await queryLists()
}

/**
 * 轮询更新任务状态
 */
const { start, end } = usePolling(checkDrawsStatus, {
    key: 'video',
    time: 1000 * 10,
    totalTime: 10 * 60 * 1000,
    callback: endDrawsCallback
})

watch(
    () => queryParams.status,
    (): void => {
        start()
    }, { immediate: true }
)
